<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
            <el-form-item label="软件包类型" prop="fileType">
                <el-select v-model="queryParams.fileType" placeholder="请选择软件包类型" clearable>
                    <el-option v-for="dict in dict.type.software_file_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="软件包代码" prop="code">
                <el-input v-model="queryParams.code" placeholder="请输入软件包代码" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="软件包名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入软件包名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="软件包版本" prop="version">
                <el-input v-model="queryParams.version" placeholder="请输入软件包版本" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['produce:product-software-package:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['produce:product-software-package:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['produce:product-software-package:removed']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['produce:product-software-package:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="ProductSoftwarePackageList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="软件包代码" align="center" prop="code" />
            <el-table-column label="软件包名称" align="center" prop="name" />
            <el-table-column label="软件包版本" align="center" prop="version" />
            <el-table-column label="软件包地址" align="center" prop="fileAddress" >
                <template slot-scope="scope">
                    <el-button size="mini" style="font-size: 15px;" type="text" @click="handleDownload(scope.row)"> 
                        链接
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="软件包类型" align="center" prop="fileType" >
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.software_file_type" :value="scope.row.fileType"/>
                </template>
            </el-table-column>
            <el-table-column label="存在的BUG" align="center" prop="existBug" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['produce:product-software-package:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['produce:product-software-package:removed']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改产品软件包文件对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="产品传感器" prop="sensor">
                    <el-select v-model="form.sensor" placeholder="产品类型" @change="getProductInfoList($event)" clearable filterable>
                        <el-option v-for="item in sensorList" :key="item.sensorCode" :label="item.sensorCode+'-'+item.sensorName"
                            :value="item.sensorCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="关联产品" prop="productCodes">
                    <el-select v-model="form.productCodes" placeholder="关联产品" @change="selectProduct($event)" @remove-tag="removeProduct($event)" @clear="removeAll($event)" clearable filterable multiple>
                        <el-option v-if="productInfoOption.length>0 && productInfoOption[0] !== null" v-for="item in productInfoOption" :key="item.productCode" :label="item.productCode +'-'+ item.productName"
                        :value="item.productCode + 'and' + item.cpuModel" />
                    </el-select>
                </el-form-item>
                <el-form-item label="CPU" prop="cpuModel">
                    <!-- <el-input v-model="form.cpuModel" placeholder="请输入CPU" /> -->
                    <el-select v-model="form.cpuModel" placeholder="请选择CPU" clearable>
                        <el-option v-for="item in this.CPUList" :key="item" :label="item"
                            :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="软件包类型" prop="fileType">
                    <el-select v-model="form.fileType" placeholder="请选择软件包类型" @change="fileTypeChange($event)">
                        <el-option v-for="dict in dict.type.software_file_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="软件包代码" prop="code" >
                    <el-input v-model="form.code" placeholder="请输入软件包代码" type="text" maxlength="4" show-word-limit/>
                </el-form-item>
                <el-form-item label="软件包名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入软件包名称" type="text" maxlength="20" show-word-limit/>
                </el-form-item>
                <el-form-item label="软件包版本" prop="version">
                    <el-input v-model="form.version" placehohandleExceedlder="请输入软件包版本" type="text" maxlength="10" show-word-limit/>
                </el-form-item>
                <el-form-item label="软件包" prop="fileAddress">
                    <!-- <file-upload-oss v-model="form.fileAddress" :fileTypeCode="2" :fileTypeName="this.fileTypeName" placeholder="请上传软件包" /> -->
                    <div class="upload-file">
                        <el-upload
                            multiple
                            :action="uploadFileUrl + '?fileTypeCode=' + this.fileTypeCode"
                            :before-upload="handleBeforeUpload"
                            :file-list="fileList"
                            :limit="limit"
                            :on-error="handleUploadError"
                            :on-exceed="handleExceed"
                            :on-success="handleUploadSuccess"
                            :show-file-list="false"
                            :headers="headers"
                            class="upload-file-uploader"
                            ref="fileUpload"
                        >
                            <!-- 上传按钮 -->
                            <el-button size="mini" type="primary">选取文件</el-button>
                            <!-- 上传提示 -->
                            <div class="el-upload__tip" slot="tip" v-if="showTip">
                            请上传
                            <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ this.fileType.join("/") }}</b> </template>
                            的文件
                            </div>
                        </el-upload>
                    
                        <!-- 文件列表 -->
                        <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
                            <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
                            <el-link :href="file.url" :underline="false" target="_blank">
                                <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
                            </el-link>
                            <div class="ele-upload-list__item-content-action">
                                <el-link :underline="false" @click="handleDeleteFile(index)" type="danger">删除</el-link>
                            </div>
                            </li>
                        </transition-group>
                    </div>
                </el-form-item>
                <el-form-item label="存在的BUG" prop="existBug">
                    <el-input type="textarea" v-model="form.existBug" placeholder="请输入存在的BUG"  maxlength="100" show-word-limit/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"  maxlength="30" show-word-limit/>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio
                        v-for="dict in dict.type.sys_normal_disable"
                        :key="dict.value"
                        :label="dict.value"
                        >{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listProductSoftwarePackage, getProductSoftwarePackage, removedProductSoftwarePackage, addProductSoftwarePackage, updateProductSoftwarePackage , changeStatus} from "@/api/produce/product-software-package";
import { listProductType } from "@/api/produce/product-type";
import { listProductInfo , productInfoBySensorCode} from "@/api/produce/product-info";
import { listProductSensor} from "@/api/produce/product-sensor";
import {  getProductSensor } from "@/api/produce/product-sensor";
import { getToken } from "@/utils/auth";

export default {
    name: "Product-software-package",
    dicts: ['software_file_type','sys_normal_disable'],
    data() {
        return {
            // url转换的文件名
            fetchFileName:'',
            // url转换的文件类型
            fetchFileType:'',
            // CPUList
            CPUList:[],
            // 上传 相关参数
            number: 0,
            uploadList: [],
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/oss-controller/upload-file", // 上传文件服务器地址
            headers: {
            Authorization: "Bearer " + getToken(),
            },
            fileList: [],
            //code:1 文本  2-软件包 3-图片 4-视频 9999-其他
            fileTypeCode : 2,
            // 文件类型, 例如['png', 'jpg', 'jpeg']
            fileType:  ["doc", "xls", "ppt", "txt", "pdf",'png', 'jpg', 'jpeg','tgz','bin','json'],
            // 文件上传数量限制
            limit: 1 ,
            // 大小限制(MB)
            fileSize: 1024,
            // 是否显示提示
            isShowTip:true,



            // 文件包类型名称
            fileTypeName:'',
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 产品软件包文件表格数据
            ProductSoftwarePackageList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                code: null,
                name: null,
                version: null,
                fileAddress: null,
                fileType: null,
                existBug: null,
                status: null,
                removed: null,
                orderByColumn:'id',
                isAsc:'desc'
            },
            // 产品类型选项
            productTypeOption: [],
            // 产品选项
            productInfoOption: [],
            // 传感器
            sensorList:[],
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                fileType: [
                    { required: true, message: "软件包类型不能为空", trigger: "blur" }
                ],
                code: [
                    { required: true, message: "软件包代码不能为空", trigger: "blur" },
                    { required: true, message: "输入规则：大小写字母、数字", trigger: "blur", pattern: /^[a-zA-Z0-9]+$/ }
                ],
                name: [
                    { required: true, message: "软件包名称不能为空", trigger: "blur" }
                ],
                version: [
                    { required: true, message: "软件包版本不能为空", trigger: "blur" }
                ],
                fileAddress: [
                    { required: true, message: "软件包地址不能为空", trigger: "blur" }
                ],
                fileType: [
                    { required: true, message: "软件包类型不能为空", trigger: "change" }
                ],
                productType: [
                    { required: true, message: "产品类型不能为空", trigger: "blur" }
                ],
                productCodes: [
                    { required: false, message: "关联产品不能为空", trigger: "blur" }
                ],
            }
        };
    },
    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
    },
    created() {
        this.getList();
        //传感器列表
        this.getSensorList()
    },
    methods: {
        /** 软件包下载 */
        handleDownload(row){
            let url = row.fileAddress
            const a = document.createElement('a')
            a.href = url
            a.download = row.fileAddress // 下载后文件名
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click() // 点击下载
            document.body.removeChild(a) // 下载完成移除元素
            // window.location.href = row.fileAddress
        },
        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            // 校检文件类型
            if (this.fileType) {
            const fileName = file.name.split('.');
            const fileExt = fileName[fileName.length - 1];
            const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
            if (!isTypeOk) {
                this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
                return false;
            }
            }
            // 校检文件大小
            if (this.fileSize) {
            const isLt = file.size / 1024 / 1024 < this.fileSize;
            if (!isLt) {
                this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
                return false;
            }
            }
            this.$modal.loading("正在上传文件，请稍候...");
            this.number++;
            return true;
        },
        // 文件个数超出
        handleExceed() {
            this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
        },
        // 上传失败
        handleUploadError(err) {
            this.$modal.msgError("上传文件失败，请重试");
            this.$modal.closeLoading()
        },
        // 上传成功回调
        handleUploadSuccess(res, file) {
            if (res.code === 200) {
            this.uploadList.push({ name: res.data.url, url: res.data.url });
            this.uploadedSuccessfully();
            } else {
            this.number--;
            this.$modal.closeLoading();
            this.$modal.msgError(res.msg);
            this.$refs.fileUpload.handleRemove(file);
            this.uploadedSuccessfully();
            }
        },
        // 删除文件
        handleDeleteFile(index) {
            this.fileList.splice(index, 1);
            this.$emit("input", this.listToString(this.fileList));
        },
        // 上传结束处理
        uploadedSuccessfully() {
            if (this.number > 0 && this.uploadList.length === this.number) {
            this.fileList = this.fileList.concat(this.uploadList);
            this.uploadList = [];
            this.number = 0;
            this.$emit("input", this.listToString(this.fileList));
            this.$modal.closeLoading();
            }
        },
        // 获取文件名称
        getFileName(name) {
            if (name.lastIndexOf("/") > -1) {
            return decodeURIComponent(name.slice(name.lastIndexOf("/") + 1)).slice(32);
            } else {
            return "";
            }
        },
        // 对象转成指定字符串分隔
        listToString(list, separator) {
            let strs = "";
            separator = separator || ",";
            for (let i in list) {
            strs += list[i].url + separator;
            }
            return strs != '' ? strs.substr(0, strs.length - 1) : '';
        },
        /** 文件包类型变更 */
        fileTypeChange(val){
            this.uploadList = [];
            this.fileList = [];
            //图像bin文件和u-boot
            if(val == '2' || val == '5'){
                this.fileType = ['bin']
            }else if(val == '4'){
                this.fileType = ['tgz']
            }else if(val == '6'){
                this.fileType = ''
            }else{
                this.fileType = ["doc", "xls", "ppt", "txt", "pdf",'png', 'jpg', 'jpeg','tgz','bin','json']
            }
            
        },
        /** 获取传感器列表 */
        getSensorList(){
            // 查询参数
            const params = {
                pageNum: 1,
                pageSize: 1000
            }
            listProductSensor(params).then(response =>{
                this.sensorList = response.rows
            })
        },
        /**查询产品类型下拉 */
        getProductType () {
            // 产品类型查询
            let productTypeQueryParams = {
                pageNum: 1,
                pageSize: 100,
            };
            listProductType(productTypeQueryParams).then(response => {
                this.productTypeOption = response.rows;
                this.loading = false;
            });
        },
        /** 清空选中产品 */
        removeAll(){
            //清空CPU集合
            this.CPUList=[]
        },
        /** 点击选择产品 */
        selectProduct(val){
            for(var i=0;i<val.length;i++){
                //拆分val，减号后面的是cpuModel值
                if(this.CPUList.indexOf(val[i].split('and')[1]) === -1){
                    this.CPUList.push(val[i].split('and')[1])
                }
            }
        },
        /** 点击移除产品 */
        removeProduct(val){
            if(this.CPUList.length>0){
                //拆分val，减号后面的是cpuModel值
                if(this.CPUList.indexOf(val.split('and')[1]) !== -1){
                    let delCpu = val.split('and')[1]
                    this.CPUList = this.CPUList.filter(item => item != delCpu)
                }
            }
        },
        /** 查询产品下拉*/
        getProductInfoList(val) {
        // 每次下拉都先清空
        this.form.productCodes = [];
        let qurey = {
            sensorCode: val
        };
        productInfoBySensorCode(qurey).then(response => {
            if(response.code === 200){
                this.productInfoOption = response.data;
                this.$forceUpdate()
            }
        }).catch((err) =>{
            this.$message({
                message: '传感器关联产品获取失败!',
                type: 'error'
            })
        }).finally(() =>{
            this.loading = false;
        });
        },
        /** 查询产品软件包文件列表 */
        getList() {
            this.loading = true;
            listProductSoftwarePackage(this.queryParams).then(response => {
                this.ProductSoftwarePackageList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                code: null,
                name: null,
                version: null,
                fileAddress: null,
                fileType: null,
                existBug: null,
                status: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                removed: null,
                productType: null ,
                productCodes: [],
            };
            this.resetForm("form");
        },
        // 状态修改
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "停用";
            this.$modal.confirm('确认要"' + text + '""' + row.name + '"吗？').then(function() {
                return changeStatus(row.id, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function() {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.getProductType();
            this.productInfoOption=[];
            this.open = true;
            this.uploadList = [];
            this.fileList = [];
            this.title = "添加产品软件包文件";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.getProductType ();
            const id = row.id || this.ids
            getProductSoftwarePackage(id).then(response => {
                this.form = response.data;
                var productInfoItem = response.data.productInfos;
                // 判断关联产品是否存在
                if (productInfoItem != null){
                    var list = [];
                    productInfoItem.forEach(function(element) {
                        list.push(element.productCode);
                    });
                    // 这里转换一下类型赋值下拉
                    this.$set(this.form, "fileType", response.data.fileType.toString());
                    this.$set(this.form, "productCodes", list);
                    this.$set(this.form, "productType", productInfoItem[0].productTypeCode);
                    // url转文件 赋值给fileList
                    // 假设有一个URL字符串
                    const url = response.data.fileAddress;
                    this.fileList[0] = {
                        name:url,
                        url:url
                    }
                }
                this.open = true;
                this.title = "修改产品软件包文件";
            });
        },
        /** 提交按钮 */
        submitForm() {
            if(this.fileList.length>0){
                this.form.fileAddress = this.fileList[0].url
            }
            // 拆分一下 productCodes 为 productCode + 
            if(this.form.productCodes.length > 0){
                for(var i=0;i<this.form.productCodes.length;i++){
                    this.form.productCodes[i] = this.form.productCodes[i].split('and')[0]
                }

            }

            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateProductSoftwarePackage(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addProductSoftwarePackage(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除产品软件包文件编号为"' + ids + '"的数据项？').then(function () {
                // 修改为逻辑删除
                return removedProductSoftwarePackage(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('produce/product-software-package/export', {
                ...this.queryParams
            }, `product-software-package_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>
